package com.hotel.service.impl;

import com.hotel.bean.Department;
import com.hotel.exception.SteduException;
import com.hotel.mapper.DeptMapper;
import com.hotel.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @CacheEvict(value = "hotel_system",key = "'departmentList'")
    @Override
    public boolean insert(Department d) throws SteduException {
        if(deptMapper.selectByDname(d.getDname()) != null){
            throw new SteduException("部门已经存在");
        }
        if(d.getDname().equals("")){
            throw new SteduException("部门名称不能为空");
        }
        return deptMapper.insert(d) == 1;
    }
    @Caching(
            evict = {
                    @CacheEvict(value = "hotel_system",key = "'departmentList'"),
                    @CacheEvict(value = "hotel_system",key = "#did")
            }
    )
    @Override
    public boolean delete(Integer did) throws SteduException {
        if(deptMapper.selectByDid(did) == null){
            throw new SteduException("部门不存在");
        }
        if(deptMapper.selectAllDeptByDid(did).size() != 0){
            throw new SteduException("部门下存在员工不允许删除!!!");
        }
        return deptMapper.delete(did) == 1;
    }
    @Caching(
            evict = {
                    @CacheEvict(value = "hotel_system",key = "'departmentList'"),
                    @CacheEvict(value = "hotel_system",key = "#d.did")
            }
    )
    @Override
    public boolean update(Department d) throws SteduException {
        if(deptMapper.selectByDid(d.getDid()) == null){
            throw new SteduException("部门不存在");
        }
        if(d.getDname().equals("")){
            throw new SteduException("部门名称不能为空");
        }
        Department d1 = deptMapper.selectByDname(d.getDname());
        if(d1 != null && d1.getDid() != d.getDid()){
            throw new SteduException("部门名称重复");
        }
        return deptMapper.update(d) == 1;
    }
    @Cacheable(value = "hotel_system" ,key = "'departmentList'",unless = "#result == null || #result.size() == 0")
    @Override
    public List<Department> selectAll() {
        return deptMapper.selectAll();
    }
    @Cacheable(value ="hotel_system",key = "#did",unless = "#result==null")
    @Override
    public Department selectByDid(Integer did) {
        return deptMapper.selectByDid(did);
    }

    @Override
    public Department selectByDname(String dname) {
        return selectByDname(dname);
    }
}
